package com.nmp.model;

import com.nmp.common.ConfigFactory;
import com.vng.chn.csm.model.leveldb.SessionModelImpl;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
//import sun.security.krb5.Config;

/**
 *
 * @author evolplus
 */
public class SessionModel {

    private static final Lock createLock_ = new ReentrantLock();
    private static SessionModel _instance = null;

    public static final String AUTH_COOKIENAME = "nmpauth";
    private static final Logger logger = Logger.getLogger(SessionModel.class);
    private static final String SESSION_EXPIRE = ConfigFactory.getParam("session_cache", "expire");
    private static final String SESSION_PATH = ConfigFactory.getParam("session_cache", "path");
    private static final int SESSION_MODEL_BLOCK_SIZE = 10;
    private static final int SESSION_MODEL_MAX_OPEN_FILE = 10;

    private SessionModelImpl sessionModelImpl = null;

    private SessionModel() {
        try {
            sessionModelImpl = new SessionModelImpl(SESSION_PATH, SESSION_MODEL_BLOCK_SIZE, SESSION_MODEL_MAX_OPEN_FILE);
        } catch (IOException ex) {
            logger.warn("Error load session snapshot.", ex);
        }
    }

    public static SessionModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new SessionModel();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    private String getSessionId(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (AUTH_COOKIENAME.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public void deleteSession(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String sessionId = getSessionId(req);
            if (sessionId != null && !sessionId.isEmpty()) {
                sessionModelImpl.deleteSession(sessionId);
                Cookie cookie = new Cookie(AUTH_COOKIENAME, sessionId);
                cookie.setPath("/");
                cookie.setHttpOnly(true);
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        } catch (Exception ex) {
            logger.error("SessionModel.deleteSession:" + ex.getMessage(), ex);
        }
    }

    public String getUserLogin(HttpServletRequest req) {
        try {
            String sessionId = getSessionId(req);
            if (sessionId != null && !sessionId.isEmpty()) {
                String rst = sessionModelImpl.getUsernameFromSession(sessionId);
                if (rst != null) {
                    return rst;
                }
            }
        } catch (Exception ex) {
            logger.error("SessionModel.getUserLogin:" + ex.getMessage(), ex);
        }
        return "";
    }

    public void setSession(String id, HttpServletRequest req, HttpServletResponse resp) {
        try {
            String sessionId = sessionModelImpl.generateSession(id, Long.parseLong(SESSION_EXPIRE));
            if (sessionId != null && !sessionId.isEmpty()) {
                Cookie cookie = new Cookie(AUTH_COOKIENAME, sessionId);
                cookie.setDomain("");
                cookie.setPath("/");
                cookie.setHttpOnly(true);
                cookie.setMaxAge(Integer.parseInt(SESSION_EXPIRE));
                resp.addCookie(cookie);
            }
        } catch (NumberFormatException ex) {
            logger.error("SessionModel.setSession:" + ex.getMessage(), ex);
        }
    }
    
    public String validateSessionId(String sessionId) {
        try {
            if (sessionId != null && !sessionId.isEmpty()) {
                String rst = sessionModelImpl.getUsernameFromSession(sessionId);
                if (rst != null) {
                    return rst;
                }
            }
        } catch (Exception ex) {
            logger.error("SessionModel.validateSessionId:" + ex.getMessage(), ex);
        }
        return "";
    }
}
